package com.efuture.jdbc;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @ClassNAME JdbcTransactionManager
 * @Description 演示JDBC事务管理 操作db3库的account表
 * @Author zhaoshanshan
 * @Date 2021/9/19 10:31 下午
 * @Version 1.0
 */
public class JdbcTransactionManager {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try{
            conn = JDBCUtils.getConnection();
            //开启事务
            conn.setAutoCommit(false);//开启事务
            String sql1 = "update account set balance = ? where id = ?";
            String sql2 = "update account set balance = ? where id = ?";
            pstmt1 =  conn.prepareStatement(sql1);
            pstmt1.setDouble(1,500);
            pstmt1.setInt(2,1);
            pstmt2 =  conn.prepareStatement(sql2);
            pstmt2.setDouble(1,1500);
            pstmt2.setInt(2,2);
            pstmt1.executeUpdate();
            System.out.println(3/0);//手动模拟异常 让事务进行回滚
            pstmt2.executeUpdate();
            conn.commit();
        }catch (Exception e){
            if(null!=conn){
                try {
                    conn.rollback();//异常事务回滚
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
           JDBCUtils.close(conn,pstmt1);
           JDBCUtils.close(null,pstmt2);
        }
    }
}